<template>
  <div class="shifts-container">
    <div class="header">
      <h2>班次管理</h2>
      <el-button type="primary" @click="showAddDialog" class="add-button">添加班次</el-button>
    </div>

    <el-table v-loading="loading" :data="shifts" style="width: 100%">
      <el-table-column prop="name" label="班次名称" />
      <el-table-column prop="product_name" label="产品" />
      <el-table-column label="班次类型">
        <template #default="{ row }">
          {{ row.is_full_day ? '全天班次' : '固定时间班次' }}
        </template>
      </el-table-column>
      <el-table-column label="上班时间">
        <template #default="{ row }">
          {{ row.is_full_day ? '全天' : formatTime(row.start_time) }}
        </template>
      </el-table-column>
      <el-table-column label="下班时间">
        <template #default="{ row }">
          {{ row.is_full_day ? '全天' : formatTime(row.end_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="shiftForm" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="shiftForm.name" />
        </el-form-item>
        <el-form-item label="产品">
          <el-select 
            v-model="selectedProduct" 
            placeholder="选择产品" 
            style="width: 100%"
            @change="handleProductChange"
            filterable
            clearable
          >
            <el-option
              v-for="product in products"
              :key="product.ID"
              :label="product.name"
              :value="product.ID"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ product.name }}</span>
                <span style="color: #8492a6; font-size: 13px">{{ product.description }}</span>
              </div>
            </el-option>
          </el-select>
          <div v-if="!products.length" style="margin-top: 8px; font-size: 12px; color: #909399;">
            <el-link type="primary" @click="goToProductManagement">前往产品管理添加产品</el-link>
          </div>
        </el-form-item>
        <el-form-item label="班次类型">
          <el-radio-group v-model="shiftForm.is_full_day">
            <el-radio :label="false">固定时间班次</el-radio>
            <el-radio :label="true">全天班次</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上班时间" v-if="!shiftForm.is_full_day">
          <el-time-picker
            v-model="shiftForm.start_time"
            format="HH:mm"
            placeholder="选择上班时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="下班时间" v-if="!shiftForm.is_full_day">
          <el-time-picker
            v-model="shiftForm.end_time"
            format="HH:mm"
            placeholder="选择下班时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="shiftForm.description"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useScheduleStore } from '../stores/schedule.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const store = useScheduleStore()
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const shifts = ref([])
const selectedProduct = ref(null)

const products = computed(() => store.products)

const shiftForm = ref({
  name: '',
  product_id: 0,
  product_name: '',
  start_time: '',
  end_time: '',
  is_full_day: false,
  description: ''
})

const resetForm = () => {
  shiftForm.value = {
    name: '',
    product_id: 0,
    product_name: '',
    start_time: '',
    end_time: '',
    is_full_day: false,
    description: ''
  }
  selectedProduct.value = null
}

const formatTime = (datetime) => {
  if (!datetime) return ''
  const date = new Date(datetime)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

const handleProductChange = () => {
  if (selectedProduct.value) {
    const product = products.value.find(p => p.ID === selectedProduct.value)
    if (product) {
      shiftForm.value.product_id = product.ID
      shiftForm.value.product_name = product.name
    }
  } else {
    shiftForm.value.product_id = 0
    shiftForm.value.product_name = ''
  }
}

const goToProductManagement = () => {
  dialogVisible.value = false
  router.push('/products')
}

const showAddDialog = () => {
  dialogTitle.value = '添加班次'
  resetForm()
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  dialogTitle.value = '编辑班次'
  
  // 创建日期对象以便于时间选择器使用
  const startTime = new Date(row.start_time)
  const endTime = new Date(row.end_time)
  
  shiftForm.value = { 
    ID: row.ID,
    name: row.name,
    product_id: row.product_id || 0,
    product_name: row.product_name || '',
    start_time: startTime,
    end_time: endTime,
    is_full_day: row.is_full_day || false,
    description: row.description
  }
  selectedProduct.value = row.product_id || null
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (!shiftForm.value.name) {
      ElMessage.error('班次名称不能为空')
      return
    }
    
    if (!shiftForm.value.is_full_day) {
      if (!shiftForm.value.start_time || !shiftForm.value.end_time) {
        ElMessage.error('上班时间和下班时间不能为空')
        return
      }
      
      // 比较时间部分
      const startHour = shiftForm.value.start_time.getHours()
      const startMinute = shiftForm.value.start_time.getMinutes()
      const endHour = shiftForm.value.end_time.getHours()
      const endMinute = shiftForm.value.end_time.getMinutes()
      
      if (endHour < startHour || (endHour === startHour && endMinute <= startMinute)) {
        ElMessage.error('下班时间必须晚于上班时间')
        return
      }
    } else {
      // 如果是全天班次，设置默认的开始和结束时间
      const today = new Date()
      
      // 设置开始时间为00:00
      const startTime = new Date(today)
      startTime.setHours(0, 0, 0, 0)
      shiftForm.value.start_time = startTime
      
      // 设置结束时间为23:59
      const endTime = new Date(today)
      endTime.setHours(23, 59, 0, 0)
      shiftForm.value.end_time = endTime
    }
    
    if (dialogTitle.value === '添加班次') {
      await store.createShift(shiftForm.value)
      ElMessage.success('添加成功')
    } else {
      await store.updateShift(shiftForm.value)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    await fetchShifts()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.error || error.message))
  }
}

const handleDelete = async (row) => {
  try {
    if (!row || !row.ID) {
      ElMessage.error('无效的班次ID')
      return
    }
    await store.deleteShift(row.ID)
    ElMessage.success('删除成功')
    await fetchShifts()
  } catch (error) {
    console.error('删除班次出错:', error)
    ElMessage.error('删除失败')
  }
}

const fetchShifts = async () => {
  loading.value = true
  try {
    await store.fetchShifts()
    shifts.value = store.shifts
  } catch (error) {
    ElMessage.error('获取班次列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    await Promise.all([
      fetchShifts(),
      store.fetchProducts()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<style scoped>
.shifts-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  max-width: 1600px;
  margin: 0 auto;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--apple-spacing-lg);
  flex-wrap: wrap;
  gap: var(--apple-spacing-sm);
}

.add-button {
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--apple-spacing-sm);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--apple-spacing-sm);
    margin-bottom: var(--apple-spacing-md);
  }
  
  .header h2 {
    margin-bottom: var(--apple-spacing-xs);
  }
  
  .add-button {
    align-self: flex-start;
  }
  
  .el-date-picker {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .el-table {
    font-size: 13px;
  }
  
  .el-button.is-small {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style>